package com.rskj.cashbook.util;

import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Pattern;

public class IpUtils {

    public static final String UN_KNOWN = "unKnown";

    /**
     * 获取客户端真实ip
     *
     * @param request request
     * @return String
     */
    public static String getRemoteIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (!StringUtils.isEmpty(ip) && !UN_KNOWN.equalsIgnoreCase(ip)) {
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if (!StringUtils.isEmpty(ip) && !UN_KNOWN.equalsIgnoreCase(ip)) {
            return ip;
        }
        return request.getRemoteAddr();
    }

    private static final Pattern IPV4_PATTERN = Pattern.compile(
            "^" +
                    "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\." + // First octet
                    "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\." + // Second octet
                    "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\." + // Third octet
                    "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"      // Fourth octet
    );

    public static boolean isMulticastIP(String ipAddress) {
        if (!isValidIPv4(ipAddress)) {
            return false;
        }

        String[] parts = ipAddress.split("\\.");
        int firstOctet = Integer.parseInt(parts[0]);

        // 检查是否为多播地址
        if (firstOctet >= 224 && firstOctet <= 239) {
            return true;
        }

        return false;
    }

    private static boolean isValidIPv4(String ipAddress) {
        return IPV4_PATTERN.matcher(ipAddress).matches();
    }

}
